/**
 * This class represents a custom rss feed parser which is used to parse
 * rss feeds for all rss feeds except the events calendar module in the 
 * iWestern application. It is a subclass of RssFeedParser and uses 
 * methods / attributes from this class when parsing the rss feed.
 * @author Chirag Mistry
 */

package ca.uwo.android.alumni;

import java.io.InputStream;

import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Xml;
import ca.uwo.android.rss.RssFeed;
import ca.uwo.android.rss.RssItem;
import ca.uwo.android.rss.SaxRssParser;

public class AlumniBranchesParser extends SaxRssParser {

	/**
	 * Constructor for the rss feed parser
	 * 
	 * @param rssFeedURL
	 *            - the url of the rss feed to parse
	 */
	public AlumniBranchesParser(String rssFeedURL) throws Exception {
		super(rssFeedURL);
	}

	/**
	 * This method parses the rss feed and returns an rss feed object containing
	 * all the feed items read in from the source
	 * @return
	 */
	public RssFeed parse() throws Exception{
		
		final RssItem currentItem = new RssItem();	//represents current item being parsed
		RootElement root = new RootElement(RSS);	//define the root element of the rss feed document
		
		final RssFeed rssItems = new RssFeed();		//rss feed object to store all rss items
		
		Element channel = root.getChild(CHANNEL);	//get the channel element from root
		
		String rssFeedText;
		
		InputStream is = this.getInputStream();	//get the input stream to the rss feed
		rssFeedText = convertSpecialChars(is);	//convert special characters in feed	
		
		
		//get each (child) item element from the channel and store it in the rss feed object
		Element item = channel.getChild(ITEM);
		item.setEndElementListener(new EndElementListener() {
			public void end() {
				rssItems.add(currentItem.copy());
			}
		});
		
		//parse and store the title of the rss feed item
		item.getChild(TITLE).setEndTextElementListener(
				new EndTextElementListener() {
					public void end(String body) {
						currentItem.setTitle(body);
					}
				});
			
		//parse the rss feed directly from the input stream using utf 8 encoding
		Xml.parse(rssFeedText, root.getContentHandler());

		return rssItems;
	}
}
